<template>
    <div class="customer-addDoc">
        <span v-if="isUpdate && updateLoading">加载中...</span>
        <Form ref="formInline" :model="formInline" :rules="ruleInline" inline>
            <div style="text-align:right;margin-bottom:5px">
                <Button v-if="!isUpdate" type="primary" @click.stop="customerAdd('formInline')" :loading="addLoading===true?true:false">保存</Button>
                <Button class="ml20" ghost type="primary" @click.stop="back">返回</Button>
            </div>
            <div class="table">
                <Row class="block">
                    <Col class="line" span="6">
                        <FormItem
                            class="list"
                            label="姓名"
                            prop="customerName">
                            <Input
                                type="text"
                                placeholder=""
                                v-model="formInline.customerName"
                                :maxlength="8"
                            />
                        </FormItem>
                        <FormItem class="list" label="手机号码" prop="mobile"><Input v-model="formInline.mobile" type="text" :maxlength="11" placeholder="" /></FormItem>
                        <FormItem class="list" label="身高(cm)" prop="customerInfo.height"><Input :maxlength="3" v-model.number="formInline.customerInfo.height" placeholder="" /></FormItem>
                        <FormItem class="list" label="患者类型" prop="customerInfo.diseaseType">
                            <Select @on-change="diseaseTypeChange" placeholder="选择患者类型" v-model="formInline.customerInfo.diseaseType">
                                <Option  class="select" v-for="item in diseaseTypeList" :value="String(item.itemKey)" :key="item.id">{{ item.itemValue }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col class="line" span="6">
                        <FormItem class="list" label="性别" prop="sex">
                            <RadioGroup class="sex" v-model.number="formInline.sex">
                                <Radio v-for="(item,i) in GLOBAL.sexOptionList" :key="i" :label="Number(item.value)">{{item.text}}</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem class="list" label="身份证号" prop="customerInfo.idCard"><Input v-model="formInline.customerInfo.idCard" type="text" :maxlength="16" placeholder="" /></FormItem>
                        <FormItem class="list" label="体重(kg)" prop="customerInfo.weight"><Input v-model.number="formInline.customerInfo.weight" type="text" :maxlength="3" placeholder="" /></FormItem>
                        <FormItem class="list" label="并发症" prop="customerInfo.complication">
                            <Select multiple v-model="formInline.customerInfo.complication" placeholder="选择并发症">
                                <Option  class="select" v-for="item in complicationOptionList" :value="item.itemValue" :key="item.id">{{ item.itemValue }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col class="line" span="6">
                        <FormItem class="list" label="出生日期" prop="birthday"><DatePicker :clearable="false" @on-change="t=>formInline.birthday=t" format="yyyy-MM-dd" type="datetime" :value="formInline.birthday" placeholder="" /></FormItem>
                        <FormItem class="list" label="联系人" prop="customerInfo.contactPerson"><Input type="text" :maxlength="5" v-model="formInline.customerInfo.contactPerson" placeholder="" /></FormItem>
                        <FormItem class="list marry" label="婚姻状态" prop="customerInfo.marryFlag">
                            <RadioGroup v-model="formInline.customerInfo.marryFlag">
                                <Radio v-for="(item,i) in marryTypeList" :key="i" :label="Number(item.itemKey)">{{item.itemValue}}</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem class="list" label="确诊年份" prop="customerInfo.careTime">
                            <DatePicker
                                @on-change="(t1) => {
                                    formInline.customerInfo.careTime = t1;
                                    formInline = {...formInline};
                                }"
                                :value="formInline.customerInfo.careTime"
                                type="datetime"
                                placeholder=""
                            />
                        </FormItem>
                    </Col>
                    <Col class="line" span="6">
                        <FormItem class="list" label="年龄" prop=""><Input disabled :value="formInline.birthday | AGE" placeholder="" /></FormItem>
                        <FormItem class="list" label="联系电话" prop="customerInfo.contactPhone"><Input v-model="formInline.customerInfo.contactPhone" :maxlength="12" placeholder="" /></FormItem>
                        <FormItem class="list" label="职业" prop="customerInfo.profession"><Input v-model="formInline.customerInfo.profession" placeholder="" /></FormItem>
                        <FormItem class="list" label="会员卡号" prop="customerInfo.vipNumber"><Input v-model="formInline.customerInfo.vipNumber" placeholder="" /></FormItem>
                    </Col>
                </Row>
                <Row class="block">
                    <Col class="line" span="12">
                        <div class="list">
                            <label style="paddingRight:10px;paddingBottom:10px;" for="">所在地址:</label>
                            <Row style="width:100%;">
                                <Col :span="8">
                                    <FormItem class="list" label="" prop="customerInfo.province">
                                        <Select @on-change="provinceChange" :value="selectProvince" class="select" placeholder="请选择省/自治区">
                                            <Option  class="select" v-for="item in provinceList" :value="item" :key="item.id">{{ item.fullname }}</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col :span="8">
                                    <FormItem class="list" label="" prop="customerInfo.city">
                                        <Select @on-change="cityChange" :value="selectCity" class="select ml5" placeholder="请选择市">
                                            <Option  class="select" v-for="item in cityList" :value="item" :key="item.id">{{ item.fullname }}</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col :span="8">
                                    <FormItem class="list" label="" prop="customerInfo.district">
                                        <Select @on-change="districtChange" :value="selectDistrict" class="select ml5" placeholder="请选择县区">
                                            <Option  class="select" v-for="item in districtList" :value="item" :key="item.id">{{ item.fullname }}</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                            </Row>
                        </div>
                    </Col>
                    <Col class="line" span="12">
                        <FormItem class="list" label="详细住址" prop="customerInfo.address">
                            <Input v-model="formInline.customerInfo.address" placeholder="" />
                        </FormItem>
                    </Col>
                </Row>
                <Row class="block">
                    <Col class="line" span="12">
                        <!-- tagList -->
                        <FormItem class="list" label="患者标签" prop="tagList">
                            <Select class="select" multiple v-model="formInline.tagList" placeholder="请选择患者标签">
                                <Option  class="select" v-for="item in tagList" :value="String(item.id)" :key="item.id">{{ item.tagName }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col class="line" span="12">
                        <FormItem class="list" label="备注说明" prop="customerInfo.remark">
                            <Input maxlength="300" v-model="formInline.customerInfo.remark" show-word-limit type="text" placeholder="请输入备注..." />
                        </FormItem>
                    </Col>
                    <Col class="line" :span="6">
						<FormItem class="list" label="服务药师" label-position="left">
							<Select v-model="formInline.doctor" class="cube" placeholder="请选择服务药师">
								<Option
									class="select"
									v-for="item in userList"
									:value="item.id"
									:key="item.id"
								>{{ item.username }}</Option>
							</Select>
						</FormItem>
					</Col>
                </Row>
                <Row v-if="isUpdate">
                    <Col class="line save" span="24">
                        <Button type="primary" :loading="updateInfoLoading" @click.stop="customerUpdateInfo">保存</Button>
                    </Col>
                </Row>
            </div>
            <div class="table">
                <h4><span>健康信息</span></h4>
                <Row class="block">
                    <Col class="line" span="12">
                        <Row>
                            <Col  :span="24">
                                <FormItem class="list" label="疾病史" prop="customerHistory.diseaseHistory">
                                    <Select class="select" multiple v-model="formInline.customerHistory.diseaseHistory" placeholder="选择疾病史">
                                        <Option class="select" v-for="item in diseaseHistoryList" :value="String(item.itemKey)" :key="item.id">{{ item.itemValue }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                      
                            <Col  :span="24">
                                <FormItem class="list" label="现病史" prop="customerHistory.nowHistory">
                                    <!-- <Input v-model="formInline.customerHistory.nowHistory" placeholder="" /> -->
                                    <Select class="select" multiple v-model="formInline.customerHistory.nowHistory" placeholder="选择现病史">
                                        <Option class="select" v-for="item in diseaseHistoryList" :value="String(item.itemKey)" :key="item.id">{{ item.itemValue }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col  :span="24">
                                <FormItem class="list" label="过敏史" prop="customerHistory.allergyHistory">
                                    <!-- allergicList -->
                                    <!-- <Input v-model="formInline.customerHistory.allergyHistory" placeholder="" /> -->
                                    <Select class="select" multiple v-model="formInline.customerHistory.allergyHistory" placeholder="选择过敏史">
                                        <Option class="select" v-for="item in allergicList" :value="String(item.itemKey)" :key="item.id">{{ item.itemValue }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                    </Col>
                    <Col class="line" span="12">
                        <Row>
                            <Col  :span="24">
                                <FormItem class="list" label="家族史" prop="customerHistory.familyHistory">
                                    <Select class="select" multiple v-model="formInline.customerHistory.familyHistory" placeholder="选择家族史">
                                        <Option class="select" v-for="item in familyHistoryList" :value="String(item.itemKey)" :key="item.id">{{ item.itemValue }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col  :span="24">
                                <FormItem class="list" label="现在治疗方式" prop="customerHistory.nowTreatment">
                                    <Select class="select" multiple v-model="formInline.customerHistory.nowTreatment" placeholder="选择现在治疗方式">
                                        <Option class="select" v-for="item in nowTreatmentList" :value="String(item.itemKey)" :key="item.id">{{ item.itemValue }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col  :span="24">
                                <FormItem class="list" label="过去治疗方式" prop="customerHistory.passTreatment">
                                    <!-- <Input v-model="formInline.customerHistory.passTreatment" placeholder="" /> -->
                                    <Select class="select" multiple v-model="formInline.customerHistory.passTreatment" placeholder="选择过去治疗方式">
                                        <Option class="select" v-for="item in nowTreatmentList" :value="String(item.itemKey)" :key="item.id">{{ item.itemValue }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                    </Col>
                </Row>
                <Row v-if="isUpdate">
                    <Col class="line save" span="24">
                        <Button type="primary" :loading="updateHistoryLoading" @click.stop="customerUpdateHistory">保存</Button>
                    </Col>
                </Row>
            </div>
            <div class="table">
                <h4><span>生活习惯</span></h4>
                <Row class="block">
                    <Col class="line" span="12">
                       <FormItem class="list" label="劳动强度" prop="customerHabit.labor">
                            <RadioGroup v-model="formInline.customerHabit.labor">
                                <Radio :label="1">轻度</Radio>
                                <Radio :label="2">中度</Radio>
                                <Radio :label="3">重度</Radio>
                                <Radio :label="4">卧床休息</Radio>
                            </RadioGroup>
                        </FormItem>
                    </col>
                    <Col class="line" span="12">
                        <FormItem class="list" label="锻炼情况" prop="customerHabit.exercise">
                            <RadioGroup v-model="formInline.customerHabit.exercise">
                                <Radio :label="1">有</Radio>
                                <Radio :label="0">无</Radio>
                            </RadioGroup>
                        </FormItem>
                    </col>
                </Row>
                <Row class="block">
                    <Col class="line" span="12">
                        <Row>
                            <Col :span="12">
                                <FormItem class="list" label="抽烟情况" prop="customerHabit.smoke">
                                    <RadioGroup v-model="formInline.customerHabit.smoke">
                                        <Radio :label="1">有</Radio>
                                        <Radio :label="0">无</Radio>
                                    </RadioGroup>
                                </FormItem>
                            </Col>
                            <Col  :span="12">
                                <FormItem class="list" label="抽烟频率" prop="customerHabit.smokeRate">
                                    <Row>
                                        <Col :span="16"><Input type="number" :maxlength="4" :max="99" :min="0" v-model.number="formInline.customerHabit.smokeRate" placeholder="" /></Col>
                                        <Col :span="8"><span class="ml10">支/天</span></Col>
                                    </Row>
                                </FormItem>
                            </Col>
                        </Row>
                    </col>
                    <Col class="line block" span="12">
                        <Row>
                            <Col :span="12">
                                <FormItem class="list" label="饮酒情况" prop="customerHabit.drink">
                                    <RadioGroup v-model="formInline.customerHabit.drink">
                                        <Radio :label="1">有</Radio>
                                        <Radio :label="0">无</Radio>
                                    </RadioGroup>
                                </FormItem>
                            </Col>
                            <Col  :span="12">
                                <FormItem class="list" label="饮酒频率" prop="customerHabit.drinkRate">
                                    <Row>
                                        <Col :span="16"><Input type="number" :maxlength="8" :max="99" :min="0" v-model.number="formInline.customerHabit.drinkRate" placeholder="" /></Col>
                                        <Col :span="8"><span class="ml10">ml/天</span></Col>
                                    </Row>
                                </FormItem>
                            </Col>
                        </Row>
                    </col>
                </Row>
                <Row v-if="isUpdate">
                    <Col class="line save" span="24">
                        <Button type="primary" :loading="updateHabitLoading" @click.stop="customerUpdateHabit">保存</Button>
                    </Col>
                </Row>
            </div>
            <div class="table">
                <h4><span>家庭成员</span></h4>
                <Row class="family">
                    <Col class="line block" span="14">
                        <Row class="list">
                            <Col span="8">关系</Col>
                            <Col span="8">姓名</Col>
                            <Col span="8">联系电话</Col>
                        </Row>
                    </col>
                    <Col class="line block" span="10">
                        <Row class="list">
                            <Col span="20">备注</Col>
                            <Col span="4">操作</Col>
                        </Row>
                    </col>
                </Row>
                
                <Row class="block">
                    <Col class="line block" span="14">
                        <Row class="list family-list" v-for="(line,j) in formInline.customerFamilyList" :key="j">
                            <Col span="8"  class="pr10">
                                <FormItem class="list" label="" prop="">
                                    <Select class="select" placeholder="父亲" v-model="line['relationship']">
                                        <Option  class="select" v-for="item in familyList" :value="Number(item.itemKey)" :key="item.id">{{ item.itemValue }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="8"  class="pr10">
                                <FormItem class="list" label="" prop="">
                                    <Input v-model="line['familyName']" placeholder="请输入姓名" />
                                </FormItem>
                            </Col>
                            <Col span="8"  class="pr10">
                                <FormItem class="list" label="" prop="">
                                    <Input type="numbber" :maxlength="11" v-model="line['familyMobile']" placeholder="请输入联系电话" />
                                </FormItem>
                            </Col>
                        </Row>
                    </col>
                    <Col class="line block" span="10" >
                        <Row class="list family-list" v-for="(line,j) in formInline.customerFamilyList" :key="j">
                            <Col span="20" class="pr10">
                                <FormItem class="list" label="" prop="">
                                    <Input v-model="line['familyRemark']" placeholder="请输入备注信息"  />
                                </FormItem>
                            </Col>
                            <Col span="4" class="list">
                                <span @click.stop="removeCustomerFamily(j)">删除</span>
                            </Col>
                        </Row>
                    </col>
                </Row>
                <Row>
                    <Col span="24">
                        <Button class="btn" type="dashed" icon="ios-add" @click.stop="addCustomerFamily">新增成员</Button>
                    </col>
                </Row>
                <Row v-if="isUpdate">
                    <Col class="line save" span="24">
                        <Button type="primary" :loading="updateFamilyLoading" @click.stop="customerUpdateFamily">保存</Button>
                    </Col>
                </Row>
            </div>
        </Form>
    </div>
</template>
<script>
import { customerAdd, customerPageQueryList, customerPageQueryInterventionList, customerUpdateInfo, customerPageQueryFollowList, customerGet, customerUpdateHistory, customerUpdateHabit, customerUpdateFamily } from '@api/customer.js'
import { mapState } from '@lib/x_.js'
import { getAddressList } from '@api/address.js'
import { dicGetItemByCode } from '@api/dic.js'
import moment from 'moment'

let totalCityList = [];
let totalDistrictList = [];
export default {
    data() {
        return {
            formInline: {
                doctor: '',
                customerName: '',
                mobile: '',
                sex: '',
                birthday: '',
                headimgurl: '',
                customerInfo: {
                    idCard: '',
                    contactPerson: '',
                    contactPhone: '',
                    height: '',
                    weight: '',
                    marryFlag:'',//是否已婚，0：不是，1：是
                    profession: '',
                    diseaseType: '',
                    complication:[],
                    careTime: '',
                    vipNumber: '',
                    province: '',
                    provinceId: '',
                    city: '',
                    cityId: '',
                    district:'',
                    districtId: '',
                    address: '',
                    remark: '', //必须
                },
                customerHistory: { //健康信息
                    nowHistory:'',
                    allergyHistory: '',
                    familyHistory: '',
                    nowTreatment: '',
                    passTreatment: '',
                    diseaseHistory: '',
                },
                customerHabit: {
                    labor: '',
                    smoke: '',
                    smokeRate: '',
                    drink: '',
                    drinkRate: '',
                    exercise: '',
                },
                customerFamilyList: [],
            },

            ruleInline: {
                customerName: [{required: true, message: '姓名不能为空', trigger: 'blur' },{ pattern: /^[\u4e00-\u9fa5]{2,}(\.[\u4e00-\u9fa5]+)?$/, message: '请输入正确的中文姓名', trigger: 'blur'}],
                mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' },{  pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur'}],
                sex: [{ required: true,type: 'number', message: '请选择性别', trigger: 'change' },{ required: true,type: 'number', message: '请选择性别', trigger: 'blur' }],
                birthday: [{required: true,  type: 'date',message: '请选择出生日期', trigger: 'blur' },],
                'customerInfo.contactPerson': [{ pattern: /^[\u4e00-\u9fa5]{2,}(\.[\u4e00-\u9fa5]+)?$/, message: '请输入正确的联系人姓名', trigger: 'blur'}],
                // 'customerInfo.contactPhone': [{  pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur'}],
                'customerInfo.height': [{required: true,type:'number', message: '请输入身高', trigger: 'blur' },{ required: true,min:0,max:250,type: 'number', message: '请输入正确的身高', trigger: 'blur' }],
                'customerInfo.weight': [{required: true,type:'number', message: '请输入体重', trigger: 'blur' },{ required: true,min:0,max:250,type: 'number', message: '请输入体重的身高', trigger: 'blur' }],
                // 'customerInfo.marryFlag': [{required: true,type:'number', message: '请选择婚姻状态', trigger: 'blur' }],
                'customerInfo.remark': [{required: true, message: '请输入备注信息', trigger: 'blur' },],
                'customerHabit.labor': [{required: true,type: 'number', message: '请选择劳动强度', trigger: 'change', }],
                'customerInfo.diseaseType': [{required: true, message: '请选择患者类型', trigger: 'change', }],
            },
            provinceList: [],
            cityList: [],
            districtList: [],
            complicationOptionList: [],
            selectProvince: {},
            selectCity: {},
            selectDistrict: {},

            updateInfoLoading: false,
            updateHistoryLoading: false,
            updateHabitLoading: false,
            updateFamilyLoading: false,
            addLoading: false,
            isUpdate: false,
            updateLoading: false,
        }
    },
    mounted(){
        this.getAddressList();
        this.addCustomerFamily()
    },
    computed: {
        ...mapState(['allergicList','diseaseTypeList','familyList','diseaseHistoryList','familyHistoryList','nowTreatmentList','tagList','userList','marryTypeList']),
    },
    methods: {
        diseaseTypeChange(t){
            const idx = this.diseaseTypeList.findIndex((item,i) => String(item.itemKey) === t);
            const { itemKey } = this.diseaseTypeList[idx];
            dicGetItemByCode({typeCode:itemKey}).then(res => {
                if (res.code === '0') {
                    this.complicationOptionList = res.data;
                } else {
                    this.modal(res,'查询并发症列表')
                }
            })
        },
        districtChange(t){
            if (t) {
                const { cidx,fullname,id } = t;
                this.formInline.customerInfo.district = fullname;
                this.formInline.customerInfo.districtId = id;
            } else {
                this.selectDistrict = {}
            }
        },
        cityChange(t){
            if (t) {
                const { cidx,fullname,id } = t;
                if (cidx && cidx.length === 2) {
                    this.formInline.customerInfo.city = fullname;
                    this.formInline.customerInfo.cityId = id;
                    this.districtList = totalDistrictList.slice(cidx[0], cidx[1])
                    this.selectCity = t;
                } else {
                    console.log('this.districtList,没有其它区域-->', t)
                }
            } else {
                this.districtList = [];
                this.selectCity = {};
            }
        },
        provinceChange(t){
            if (t) {
                const { cidx,fullname,id } = t;
                this.formInline.customerInfo.province = fullname;
                this.formInline.customerInfo.provinceId = id;
                this.cityList = totalCityList.slice(cidx[0], cidx[1]);
                this.selectProvince = t;
            } else {
                this.cityList = [];
                this.selectProvince = {};
            }
            
        },
        async getAddressList() {
            const res = await getAddressList()
            this.provinceList = res[0];
            totalCityList = res[1];
            totalDistrictList = res[2];
            this.customerGet();
        },
        
        modal(res,title){
            if (res.code === "0") {
                this.$Modal.success({
                    title: title,
                    content: res.data,
                })
            } else {
                this.$Modal.warning({
                    title: title,
                    content: res.errMsg
                })
            }
        },
        customerUpdateFamily() {
            if (this.updateFamilyLoading) return;
            this.updateFamilyLoading = true;
            const { customerFamilyList,id } = this.formInline;
            customerFamilyList.map((item,i) => {
                customerFamilyList[i] = {
                    familyMobile: item.familyMobile,
                    familyRemark: item.familyRemark,
                    relationship: item.relationship,
                    familyName: item.familyName,
                }
            })
            customerUpdateFamily({customerFamilyList,id}).then(res => {
                this.updateFamilyLoading = false;
                res.code === '0' && this.customerGet()
                this.modal(res,'修改家庭成员')
            }).catch(err => {
                this.updateFamilyLoading = false;
                this.modal(res,'修改家庭成员')
            })
        },
        customerUpdateHabit() {
            if (this.formInline.customerHabit.drinkRate) {
                if (parseInt(this.formInline.customerHabit.drinkRate) !== Number(this.formInline.customerHabit.drinkRate)) {
                    return this.$Message.error('请输入整数倍的饮酒数量!');
                }
            }
            if (this.formInline.customerHabit.smokeRate) {
                if (parseInt(this.formInline.customerHabit.smokeRate) !== Number(this.formInline.customerHabit.smokeRate)) {
                    return this.$Message.error('请输入整数倍的抽烟数量!');
                }
            }
            
            if (this.updateHabitLoading) return;
            this.updateHabitLoading = true;
            const { customerHabit,id } = this.formInline


            customerUpdateHabit({ customerHabit,id}).then(res => {
                this.updateHabitLoading = false;
                res.code === '0' && this.customerGet()
                this.modal(res,'修改生活习惯')
            }).catch(err => {
                this.updateHabitLoading = false;
                this.modal(res,'修改生活习惯')
            })
        },
        customerUpdateHistory() {
            if (this.updateHistoryLoading) return;
            this.updateHistoryLoading = true;
            const { customerHistory ,id } = this.formInline
            customerHistory.diseaseHistory ? customerHistory.diseaseHistory = customerHistory.diseaseHistory.join(",") : null;
            customerHistory.familyHistory  ? customerHistory.familyHistory  = customerHistory.familyHistory.join(",")  : null;
            customerHistory.nowTreatment   ? customerHistory.nowTreatment   = customerHistory.nowTreatment.join(",")   : null;
            customerHistory.passTreatment  ? customerHistory.passTreatment  = customerHistory.passTreatment.join(",")  : null;
            customerHistory.allergyHistory ? customerHistory.allergyHistory = customerHistory.allergyHistory.join(",") : null;
            customerHistory.nowHistory     ? customerHistory.nowHistory = customerHistory.nowHistory.join(",") : null;

            customerUpdateHistory({customerHistory,id}).then(res => {
                this.updateHistoryLoading = false;
                this.modal(res,'修改健康信息')
                res.code === '0' && this.customerGet()

            }).catch(err => {
                this.updateHistoryLoading = false;
                this.modal(res,'修改健康信息')
            })
        },
        customerUpdateInfo() {
            if (!this.formInline.customerName) {
                return this.$Message.error('请输入正确的患者姓名!');
            }
            if (!String(this.formInline.sex)) {
                return this.$Message.error('请选择患者性别!');
            }
            if (!this.formInline.birthday) {
                return this.$Message.error('请选择出生日期!');
            }
            if (this.formInline.birthday) {
                const timeStamp = new Date(this.formInline.birthday).valueOf()
                const now = new Date().valueOf()
                const gap = now - timeStamp;
                const age = Math.ceil(gap/(1000*60*60*24*365))
                if (age <= 16) {
                    return this.$Message.error('患者年龄不能小于16岁!'); 
                }
            }
            if (!this.formInline.mobile) {
                return this.$Message.error('请输入患者手机号码!');
            }
            if (!this.formInline.customerInfo.height || this.formInline.customerInfo.height<=0 || this.formInline.customerInfo.height > 250) {
                return this.$Message.error('请输入正确身高!');
            }
            if (!this.formInline.customerInfo.weight || this.formInline.customerInfo.weight<=0 || this.formInline.customerInfo.weight > 250) {
                return this.$Message.error('请输入正确体重!');
            }
            if (!this.formInline.customerInfo.weight || this.formInline.customerInfo.weight<=0 || this.formInline.customerInfo.weight > 250) {
                return this.$Message.error('请输入正确体重!');
            }
            if (!this.formInline.customerInfo.diseaseType.length) {
                return this.$Message.error('请选择患者类型!');
            }
            if (!this.formInline.customerInfo.remark) {
                return this.$Message.error('请输入备注信息!');
            }

            if(this.updateInfoLoading) return;
            this.updateInfoLoading = true;
            this.formInline.birthday = moment(this.formInline.birthday).format('YYYY-MM-DD HH:mm:ss')
            const { customerName, mobile, sex, birthday, headimgurl,customerInfo, tagList, id } = this.formInline;
            customerInfo.complication ? customerInfo.complication = customerInfo.complication.join(",") : null;
            customerUpdateInfo({
               customerName, mobile, sex, birthday, headimgurl,customerInfo, tagList, id
            }).then(res => {
                this.updateInfoLoading = false;
                this.modal(res,'修改基本信息')
                res.code === '0' && this.customerGet()
            }).catch(err => {
                this.updateInfoLoading = false;
                this.modal(res,'修改基本信息')
            })
        },
        customerGet(){
            const { id , update} = this.$route.query;
            if (update) {
                this.isUpdate = true;
            }
            if (!id) {
                return this.reset()
            };
            this.updateLoading = true;
            customerGet({id}).then(res => {

                if (res.code === '0') {
                    const { data } = res;
                    Object.keys(data).map((item,i) => {
                        if (data[item]) {
                            this['formInline'][item] = data[item]
                        }
                    })
                    const { customerTags } = this.formInline;

                    customerTags.map((item,i) => customerTags[i] = String(item.tagId))
                    this.formInline.tagList = customerTags;
                    const { customerHistory ,customerInfo } = this.formInline;
                    customerHistory.diseaseHistory ? customerHistory.diseaseHistory = customerHistory.diseaseHistory.split(",") : null
                    customerHistory.nowHistory     ? customerHistory.nowHistory     = customerHistory.nowHistory.split(",") : null
                    customerHistory.familyHistory  ? customerHistory.familyHistory  = customerHistory.familyHistory.split(",") : null
                    customerHistory.nowTreatment   ? customerHistory.nowTreatment   = customerHistory.nowTreatment.split(",") : null
                    customerHistory.passTreatment  ? customerHistory.passTreatment  = customerHistory.passTreatment.split(",") : null
                    customerHistory.allergyHistory ? customerHistory.allergyHistory = customerHistory.allergyHistory.split(",")   : null
                    customerInfo.complication      ? customerInfo.complication      = customerInfo.complication.split(",") : null

                    const { provinceId, cityId, districtId } = this.formInline.customerInfo;
                    const { diseaseType } = customerInfo;
                    if (diseaseType) {
                        this.diseaseTypeChange(diseaseType)
                    }
                    if (provinceId) {
                        const idx = this.provinceList.findIndex(item => item.id === provinceId);
                        this.selectProvince = this.provinceList[idx];
                        this.provinceChange(this.provinceList[idx])
                    }
                    if (cityId) {
                        const idx = this.cityList.findIndex(item => item.id === cityId)
                        this.selectCity = this.cityList[idx]
                        this.cityChange(this.cityList[idx])
                    }
                    if (districtId) {
                        const idx = this.districtList.findIndex(item => item.id === districtId)
                        this.selectDistrict = this.districtList[idx]
                        this.districtChange(this.districtList[idx])
                    }
                    this.formInline = {...this.formInline}
                } else {
                    this.$Modal.warning({
                        title: '查询患者档案',
                        content: res.errMsg
                    })
                }
                this.updateLoading = false;
            }).catch(err => this.updateLoading = false)
        },
        // treatment
        customerAdd(name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                   console.log("验证成功")
                } else {
                    // this.$Message.error('信息不完整!');
                }
            })
            if (!String(this.formInline.sex)) {
                return this.$Message.error('请选择患者性别!');
            }
            if (!this.formInline.birthday) {
                return this.$Message.error('请选择出生日期!');
            }
            if (this.formInline.birthday) {
                this.formInline.birthday = moment(this.formInline.birthday).format('YYYY-MM-DD HH:mm:ss')
                const timeStamp = new Date(this.formInline.birthday).valueOf()
                const now = new Date().valueOf()
                const gap = now - timeStamp;
                const age = Math.ceil(gap/(1000*60*60*24*365))
                if (age <= 16) {
                    return this.$Message.error('患者年龄不能小于16岁!'); 
                }
            }
            if (!this.formInline.customerName) {
                return this.$Message.error('请输入正确的患者姓名!');
            }
            if (!this.formInline.mobile) {
                return this.$Message.error('请输入患者手机号码!');
            }
            if (!this.formInline.customerInfo.height || this.formInline.customerInfo.height<=0 || this.formInline.customerInfo.height > 250) {
                return this.$Message.error('请输入正确身高!');
            }
            if (!this.formInline.customerInfo.weight || this.formInline.customerInfo.weight<=0 || this.formInline.customerInfo.weight > 250) {
                return this.$Message.error('请输入正确体重!');
            }
            if (!this.formInline.customerInfo.weight || this.formInline.customerInfo.weight<=0 || this.formInline.customerInfo.weight > 250) {
                return this.$Message.error('请输入正确体重!');
            }
            if (!this.formInline.customerInfo.diseaseType.length) {
                return this.$Message.error('请选择患者类型!');
            }
            if (!this.formInline.customerInfo.remark) {
                return this.$Message.error('请输入备注信息!');
            }

            if (this.formInline.customerHabit.drinkRate) {

                if (parseInt(this.formInline.customerHabit.drinkRate) !== Number(this.formInline.customerHabit.drinkRate)) {
                    return this.$Message.error('请输入整数倍的饮酒数量!');
                }
            }
            if (this.formInline.customerHabit.smokeRate) {
                if (parseInt(this.formInline.customerHabit.smokeRate) !== Number(this.formInline.customerHabit.smokeRate)) {
                    return this.$Message.error('请输入整数倍的抽烟数量!');
                }
            }

            const { customerHistory,customerInfo } = this.formInline;
            customerHistory.diseaseHistory ? customerHistory.diseaseHistory = customerHistory.diseaseHistory.join(",") : null;
            customerHistory.nowHistory     ? customerHistory.nowHistory     = customerHistory.nowHistory.join(",")     : null;
            customerHistory.familyHistory  ? customerHistory.familyHistory  = customerHistory.familyHistory.join(",")  : null;
            customerHistory.nowTreatment   ? customerHistory.nowTreatment   = customerHistory.nowTreatment.join(",")   : null;
            customerHistory.passTreatment  ? customerHistory.passTreatment  = customerHistory.passTreatment.join(",")  : null;
            customerHistory.allergyHistory ? customerHistory.allergyHistory = customerHistory.allergyHistory.join(",") : null;
            customerInfo.complication      ? customerInfo.complication      = customerInfo.complication.join(",")      : null;

            if(this.addLoading)return;
            this.addLoading=true
            customerAdd({...this.formInline,...customerHistory,...customerInfo}).then(res => {

                this.modal(res,'建档')
                this.addLoading = false;
                if (res.code === "0") {
                    this.$router.push("/customer")
                }
            }).catch(err => {
                this.addLoading = false;
                this.$Modal.success({
                    title: '建档',
                    content: err.errMsg
                })
            })
        },
        removeCustomerFamily(j){
            this.formInline.customerFamilyList.splice(j,1)
            this.formInline = {...this.formInline}
        },
        addCustomerFamily() {
            this.formInline.customerFamilyList.push({
                relationship: '',
                familyName: '',
                familyMobile: '',
                familyRemark: '',
            })
            this.formInline = {...this.formInline}
        },
        back() {
            const that = this;
            this.$Modal.confirm({
                title: '返回',
                content:`确认退出${this.isUpdate?'修改':'建档'}吗?`,
                onOk() {
                    that.$router.back()
                }
            })
        },
        reset() {
            this.formInline = {
                doctor: '',
                customerName: '',
                mobile: '',
                sex: '',
                birthday: '',
                headimgurl: '',
                customerInfo: {
                    idCard: '',
                    contactPerson: '',
                    contactPhone: '',
                    height: '',
                    weight: '',
                    marryFlag:'',//是否已婚，0：不是，1：是
                    profession: '',
                    diseaseType: '',
                    complication:[],
                    careTime: '',
                    vipNumber: '',
                    province: '',
                    provinceId: '',
                    city: '',
                    cityId: '',
                    district:'',
                    districtId: '',
                    address: '',
                    remark: '', //必须
                },
                customerHistory: { //健康信息
                    nowHistory:'',
                    allergyHistory: '',
                    familyHistory: '',
                    nowTreatment: '',
                    passTreatment: '',
                    diseaseHistory: '',
                },
                customerHabit: {
                    labor: '',
                    smoke: '',
                    smokeRate: '',
                    drink: '',
                    drinkRate: '',
                    exercise: '',
                },
                customerFamilyList: [],
            }
        }
    },
    watch: {
        $route(after){
            
            this.getAddressList();
            this.addCustomerFamily()
        }
    }
}
</script>
<style lang="scss">
.customer-addDoc{

    height: 100%;
    overflow-y: scroll;
    .ivu-icon-ios-loading{
        display: none !important;
    }
    .save{
        text-align: right;
    }
    .ivu-form-item-content{
        flex: 1;
    }
    .drink,.sex{
        white-space: nowrap;
    }
    background-color: #fff;
    .pr10{
        padding-right: 10px;
    }
    .ml5{
        margin-left: 5px;
    }
    .mr10{
        margin-right: 10px;
    }
    .select{
            width: 100%;
            >div{
                width: 100%;
            }
        }
        h4{
            font-size: 14px;
            font-weight: normal;
            span{
                position: relative;
                top: -22px;
                background-color: #fff;
                padding-left: 10px;
                padding-right: 10px;
            }
        }
        .table{
            margin-bottom: 30px;
            border: 1px solid #e3e8ee;
            padding: 10px;
        }
        .block{
            .list{
                display: flex;
                line-height: 1.8em;
                align-items: center;
                margin-bottom: 20px;
                >label{
                    min-width: 90px;
                    text-align: right;
                    margin-right: 10px;
                    white-space: nowrap;
                    overflow: hidden;
                }
                span{
                    flex: 1;
                }
                .flex2{
                    flex: 2;
                }
            }
            .radio{
                border-color: transparent;
                background-color: transparent;
            }
            .marry{
                line-height: 30px;
            }
        
        
    }
    .family{
        .list{
            margin-bottom: 0;
            background-color: #F8F8F9;
            line-height: 40px;
        }
        
    }
    .family-list{
        margin-bottom: 0 !important;
        margin-top: 10px;
        line-height: auto;
    }
    .btn{
        width: 100%;
    }
}
    
</style>